/*
 * Filename:    EvaluationRuleServiceImpl.java
 * Copyright:   2015 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2015-1-29
 */
package com.paic.mhis.hcpms.evaluation.evaluationRule.intergration.dao.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.evaluation.evaluationRule.constants.Constants;
import com.paic.mhis.hcpms.evaluation.evaluationRule.dao.EvaluationRuleDao;
import com.paic.mhis.hcpms.evaluation.evaluationRule.dto.EvaluationCategoryDTO;
import com.paic.mhis.hcpms.evaluation.evaluationRule.dto.EvaluationContentDTO;
import com.paic.mhis.hcpms.evaluation.evaluationRule.dto.EvaluationMarkRuleDTO;
import com.paic.mhis.hcpms.evaluation.evaluationRule.dto.EvaluationMarkValueDTO;
import com.paic.mhis.hcpms.evaluation.evaluationRule.dto.EvaluationStandardScoreContentDTO;
import com.paic.mhis.hcpms.evaluation.evaluationRule.dto.EvaluationTypeDTO;
import com.paic.mhis.hcpms.evaluation.evaluationRule.intergration.dao.IEvaluationRuleService;

@Component("evaluationRuleServiceImpl")
public class EvaluationRuleServiceImpl implements IEvaluationRuleService {

	@Autowired
	private EvaluationRuleDao evaluationRuleDao;
	@Autowired
	private CommonDAO commonDao;

	/**
	 * 加载考评规则信息
	 */
	@Override
	public List<EvaluationCategoryDTO> loadEvaluationRules(Map<String, Object> map) {
		List<EvaluationCategoryDTO> list = null;
		String categoryType = (String) map.get("categoryType");
		String ruleId = (String) map.get("id");
		if (Constants.catetory_01.equals(categoryType)) {
			list = this.getOrgEvaluationCategory(Constants.catetory_01, ruleId);
		} else if (Constants.catetory_02.equals(categoryType)) {
			list = this.getOrgEvaluationCategory(Constants.catetory_02, ruleId);
		}

		return list;
	}

	/**
	 * 获取定点医疗机构的考评规则集合
	 * 
	 * @return
	 */
	private List<EvaluationCategoryDTO> getOrgEvaluationCategory(String categoryType, String ruleId) {

		List<EvaluationCategoryDTO> firstList = this.evaluationRuleDao.queryEvaluationCategory(categoryType, ruleId);

		if (firstList != null && firstList.size() > 0) {

			for (EvaluationCategoryDTO ruleBean : firstList) {

				String id = ruleBean.getId();

				BigDecimal score = this.evaluationRuleDao.getEvaluationRuleAllScore(id);

				ruleBean.setCategoryScore(score);

				List<EvaluationContentDTO> contentList = this.evaluationRuleDao.queryEvaluationContentDTO(id);

				ruleBean.setList(contentList); // 设置规则下面的考核内容

				if (contentList != null && contentList.size() > 0) {

					for (EvaluationContentDTO contentBean : contentList) {

						String contentId = contentBean.getId();

						List<EvaluationMarkRuleDTO> markRuleList = this.evaluationRuleDao
								.queryEvaluationMarkRuleDTO(contentId);

						contentBean.setList(markRuleList); // 设置考核内容下面的扣分细则

						if (markRuleList != null && markRuleList.size() > 0) {

							for (EvaluationMarkRuleDTO markRuleBean : markRuleList) {

								BigDecimal upperValue = markRuleBean.getUpperValue();
								BigDecimal lowerValue = markRuleBean.getLowerValue();
								if (upperValue != null && lowerValue != null) {
									markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + lowerValue + "-"
											+ upperValue + "分");
								} else if (upperValue != null) {
									markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + upperValue + "分");
								} else if (lowerValue != null) {
									markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + lowerValue + "分");
								}

								String markRuleId = markRuleBean.getId();

								List<EvaluationMarkValueDTO> markValueList = this.evaluationRuleDao
										.queryEvaluationMarkValueDTO(markRuleId);

								markRuleBean.setList(markValueList); // 设置扣分细则下面的扣分值

							}
						}

					}
				}

			}
		}

		return firstList;

	}

	/**
	 * 删除考评规则信息
	 */
	@Transactional
	@Override
	public void deleteEvaluationCategory(String[] categoryIds, String categoryType) {
		if (categoryIds != null && categoryIds.length > 0) {
			for (String id : categoryIds) {
				this.evaluationRuleDao.deleteEvaluationMarkValue(id, null);
				this.evaluationRuleDao.deleteEvaluationMarkInfo(id, null);
				this.evaluationRuleDao.deleteEvaluationContent(id, null);
				this.evaluationRuleDao.deleteEvaluationRule(id);

			}

		}

	}

	/**
	 * 加载所有的考评类别
	 * 
	 * @param scoreType
	 *            0医院，2 药店
	 * @return
	 */
	@Override
	public List<EvaluationTypeDTO> loadAllEvaluationType(String scoreType) {

		List<EvaluationTypeDTO> list = this.evaluationRuleDao.queryAllRuleType(scoreType);

		return list;
	}

	/**
	 * 根据对应的考评类别和评分类别加载树状参数
	 * 
	 * @param standardTypeId
	 * @param scoreType
	 * @return
	 */
	@Override
	public List<EvaluationStandardScoreContentDTO> loadAllTreeContent(String standardTypeId, String scoreType) {

		List<EvaluationStandardScoreContentDTO> list = this.evaluationRuleDao.queryStandardScore(standardTypeId,
				Constants.score_level_2, scoreType);

		if (list != null && list.size() > 0) {
			for (EvaluationStandardScoreContentDTO bean : list) {
				String id = bean.getId();
				bean.setParentId(standardTypeId);

				if (bean.getUpperValue() != null) {
					bean.setName(bean.getName() + " " + bean.getUpperValue() + "分");
				}

				List<EvaluationStandardScoreContentDTO> childList = this.evaluationRuleDao.queryStandardScore(id,
						Constants.score_level_3, scoreType);

				if (childList != null && childList.size() > 0) {

					for (EvaluationStandardScoreContentDTO childBean : childList) {
						childBean.setParentId(id);

						BigDecimal upperScore = childBean.getUpperValue();
						BigDecimal lowerScore = childBean.getLowerValue();
						if (upperScore != null && lowerScore != null) {
							childBean.setName(childBean.getName() + " " + upperScore + "-" + lowerScore + "分");
						} else if (upperScore != null) {
							childBean.setName(childBean.getName() + " " + upperScore + "分");
						} else if (lowerScore != null) {
							childBean.setName(childBean.getName() + " " + lowerScore + "分");
						}

					}

					bean.setList(childList);
				}

			}
		}

		return list;
	}

	@Transactional
	@Override
	public void saveEvaluationRuleInfo(List<EvaluationStandardScoreContentDTO> currentList,
			EvaluationCategoryDTO ruleBean, UserDetails user) {
		String ruleId = this.commonDao.getUUID();
		ruleBean.setId(ruleId);
		ruleBean.setIsValid(Constants.is_valid_0);
		ruleBean.setUpdateUser(user.getUsername());
		ruleBean.setCreateUser(user.getUsername());

		this.evaluationRuleDao.saveEvualtionRuleInfo(ruleBean);

		if (currentList != null && currentList.size() > 0) {

			for (EvaluationStandardScoreContentDTO bean : currentList) {

				EvaluationContentDTO contentBean = new EvaluationContentDTO();

				String contentId = this.commonDao.getUUID();
				contentBean.setId(contentId);
				contentBean.setRuleId(ruleId);
				contentBean.setStandardScoreId(bean.getId());
				contentBean.setIsValid(Constants.is_valid_0);
				contentBean.setUpdateUser(user.getUsername());
				contentBean.setCreateUser(user.getUsername());

				this.evaluationRuleDao.saveEvaluationContentInfo(contentBean);

				List<EvaluationStandardScoreContentDTO> childList = bean.getList();
				if (childList != null && childList.size() > 0) {

					for (EvaluationStandardScoreContentDTO childBean : childList) {

						EvaluationMarkRuleDTO markValueBean = new EvaluationMarkRuleDTO();
						markValueBean.setContentId(contentId);
						markValueBean.setStandardScoreId(childBean.getId());
						markValueBean.setIsValid(Constants.is_valid_0);
						markValueBean.setUpdateUser(user.getUsername());
						markValueBean.setCreateUser(user.getUsername());
						this.evaluationRuleDao.saveEvaluationMarkInfo(markValueBean);

					}
				}

			}
		}

	}

	@Transactional
	@Override
	public void updateEvaluationRuleInfo(List<EvaluationStandardScoreContentDTO> currentList,
			EvaluationCategoryDTO ruleBean, UserDetails user) {

		ruleBean.setIsValid(Constants.is_valid_0);
		ruleBean.setUpdateUser(user.getUsername());
		ruleBean.setCreateUser(user.getUsername());
		this.evaluationRuleDao.updateEvaluationRuleInfo(ruleBean);

		String categoryId = ruleBean.getId();

		// /数据库中的考核内容集合
		List<EvaluationContentDTO> accessContentList = this.evaluationRuleDao.queryEvaluationContentDTO(categoryId);

		List<EvaluationStandardScoreContentDTO> existList = new ArrayList<EvaluationStandardScoreContentDTO>();

		// /处理扣分细则
		if (currentList != null && currentList.size() > 0) {

			for (EvaluationStandardScoreContentDTO innertContent : currentList) {

				String scoreId = innertContent.getId();

				if (accessContentList != null && accessContentList.size() > 0) {

					for (int i = 0; i < accessContentList.size(); i++) {
						EvaluationContentDTO contentBean = accessContentList.get(i);
						String contentStandardScoreId = contentBean.getStandardScoreId(); // 考核内容id
						if (scoreId.equals(contentStandardScoreId)) {
							existList.add(innertContent);
							accessContentList.remove(i);
							break;
						}
					}

				}

			}

			if (existList != null && existList.size() > 0) {

				// 将accessContentList 集合中剩下的全部删除掉
				if (accessContentList != null && accessContentList.size() > 0) {

					for (EvaluationContentDTO contentBean : accessContentList) {
						String contentStandardScoreId = contentBean.getStandardScoreId(); // 考核内容id
						this.evaluationRuleDao.deleteEvaluationMarkValue(categoryId, contentStandardScoreId);
						this.evaluationRuleDao.deleteEvaluationMarkInfo(categoryId, contentStandardScoreId);
						this.evaluationRuleDao.deleteEvaluationContent(categoryId, contentStandardScoreId);
					}

				}
				// 从currentList 集合中排除掉existList 的数据后的剩下来的新增到数据库中

				for (EvaluationStandardScoreContentDTO existContent : existList) {
					String contentStandardScoreId = existContent.getId(); // 考核内容id

					for (int i = 0; i < currentList.size(); i++) {

						EvaluationStandardScoreContentDTO existInnerBean = currentList.get(i);
						String existInnerBeanId = existInnerBean.getId();
						if (contentStandardScoreId.equals(existInnerBeanId)) {
							currentList.remove(i);
							break;
						}
					}

				}

				if (currentList != null && currentList.size() > 0) {

					for (EvaluationStandardScoreContentDTO bean : currentList) {

						EvaluationContentDTO contentBean = new EvaluationContentDTO();

						String contentId = this.commonDao.getUUID();
						contentBean.setId(contentId);
						contentBean.setRuleId(categoryId);
						contentBean.setStandardScoreId(bean.getId());
						contentBean.setIsValid(Constants.is_valid_0);
						contentBean.setUpdateUser(user.getUsername());
						contentBean.setCreateUser(user.getUsername());

						this.evaluationRuleDao.saveEvaluationContentInfo(contentBean);

						List<EvaluationStandardScoreContentDTO> childList = bean.getList();
						if (childList != null && childList.size() > 0) {

							for (EvaluationStandardScoreContentDTO childBean : childList) {

								EvaluationMarkRuleDTO markValueBean = new EvaluationMarkRuleDTO();
								markValueBean.setContentId(contentId);
								markValueBean.setStandardScoreId(childBean.getId());
								markValueBean.setIsValid(Constants.is_valid_0);
								markValueBean.setUpdateUser(user.getUsername());
								markValueBean.setCreateUser(user.getUsername());
								this.evaluationRuleDao.saveEvaluationMarkInfo(markValueBean);

							}
						}

					}
				}

				// 处理existList集合中的对象的扣分细则问题
				this.processMarkValueExitsList(existList, categoryId);

			} else if (existList != null && existList.size() == 0) { // 前台提交过来的考核内容在数据库中没有
				// 则将currentList 集合中的数据新增到库中,将accessContentList 集合全部删掉
				this.processExitsList(currentList, categoryId, user);
			}

		}

	}

	private void processMarkValueExitsList(List<EvaluationStandardScoreContentDTO> existList, String ruleId) {

		if (existList != null && existList.size() > 0) {
			for (EvaluationStandardScoreContentDTO bean : existList) {
				String keyId = bean.getPrimaryId();
				List<EvaluationStandardScoreContentDTO> childList = bean.getList();
				this.processChildList(childList, keyId, ruleId);

			}
		}

	}

	private void processChildList(List<EvaluationStandardScoreContentDTO> childList, String markInfoId, String ruleId) {
		List<EvaluationMarkRuleDTO> markValueList = this.evaluationRuleDao.queryEvaluationMarkRuleDTO(markInfoId);

		if (childList != null && childList.size() > 0) {
			for (EvaluationStandardScoreContentDTO childBean : childList) {

				String starndarScordId = childBean.getId();

				for (int i = 0; i < markValueList.size(); i++) {
					EvaluationMarkRuleDTO markValueBean = markValueList.get(i);
					String markValueId = markValueBean.getStandardScoreId();

					if (starndarScordId.equals(markValueId)) {
						markValueList.remove(i);
						break;
					}

				}
			}

			// 删除剩下的markValueList

			if (markValueList != null && markValueList.size() > 0) {
				for (int i = 0; i < markValueList.size(); i++) {
					EvaluationMarkRuleDTO markValueBean = markValueList.get(i);
					this.evaluationRuleDao.deleteEvaluationMarkRuleValueByMarkInfoId(markValueBean.getId());
					this.evaluationRuleDao.deleteEvaluationMarkValueById(markValueBean.getId());
				}
			}
		}
	}

	private void processExitsList(List<EvaluationStandardScoreContentDTO> currentList, String ruleId, UserDetails user) {
		this.evaluationRuleDao.deleteEvaluationMarkValue(ruleId, null);
		this.evaluationRuleDao.deleteEvaluationMarkInfo(ruleId, null);
		this.evaluationRuleDao.deleteEvaluationContent(ruleId, null);

		if (currentList != null && currentList.size() > 0) {

			for (EvaluationStandardScoreContentDTO bean : currentList) {

				EvaluationContentDTO contentBean = new EvaluationContentDTO();

				String contentId = this.commonDao.getUUID();
				contentBean.setId(contentId);
				contentBean.setRuleId(ruleId);
				contentBean.setStandardScoreId(bean.getId());
				contentBean.setIsValid(Constants.is_valid_0);
				contentBean.setUpdateUser(user.getUsername());
				contentBean.setCreateUser(user.getUsername());

				this.evaluationRuleDao.saveEvaluationContentInfo(contentBean);

				List<EvaluationStandardScoreContentDTO> childList = bean.getList();
				if (childList != null && childList.size() > 0) {

					for (EvaluationStandardScoreContentDTO childBean : childList) {

						EvaluationMarkRuleDTO markValueBean = new EvaluationMarkRuleDTO();
						markValueBean.setContentId(contentId);
						markValueBean.setStandardScoreId(childBean.getId());
						markValueBean.setIsValid(Constants.is_valid_0);
						markValueBean.setUpdateUser(user.getUsername());
						markValueBean.setCreateUser(user.getUsername());
						this.evaluationRuleDao.saveEvaluationMarkInfo(markValueBean);

					}
				}

			}
		}

	}

	@Transactional
	@Override
	public void processMarkRuleInfo(String markRuleId, List<EvaluationMarkValueDTO> list, UserDetails user) {

		this.evaluationRuleDao.deleteEvaluationMarkRuleValueByMarkInfoId(markRuleId);

		if (list != null && list.size() > 0) {
			for (EvaluationMarkValueDTO bean : list) {
				if (Constants.is_valid_0.equals(bean.getIsValid())) {
					this.evaluationRuleDao.saveEvaluationMarkRuleValue(bean);
				}

			}
		}

	}
}
